﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ReporterEngine.Methods
{
    public class Types : BaseMethod
    {
        public override bool IsUseable(LexPath.PathToken token)
        {
            return token.Kind == LexPath.TokenKind.Method && (string.IsNullOrEmpty(token.PathExp) || token.PathExp.ToLower() == "types");
        }

        public override sQuery Execute(LexPath.PathToken token, sQuery query)
        {
            var result = query.New();

            //add elements of type
            
            //token.Args
            var typeList = query.GetArgValuesForType(token.Args);

            if (query.Elements.Count == 1 && query.Elements[0].Name.LocalName.ToLower() == "notebook")
            {
                foreach (var typeName in typeList)
                {
                    var clearName = typeName.ToLower();

                    var modelType =
                        query._model.ModelTypes.Where(
                            x => x.Label.ToLower() == clearName || x.PluralLabel.ToLower() == clearName).FirstOrDefault();

                    if (modelType != null)
                    {
                        result.Elements.AddRange(modelType.Nodes);
                    }
                }
            }
            else
            {
                foreach (var element in query.Elements)
                {
                    foreach (var name in typeList)
                    {
                        if (name.ToLower() == query._model.GetTypeName(element).ToLower() || name.ToLower() == query._model.GetPlularTypeName(element).ToLower())
                            result.Elements.Add(element);
                    }
                }
            }

            result.Elements = result.Elements.Distinct(new CIFModel.NodeComparer()).ToList();

            result.Elements = result.Elements.OrderBy(x => query._model.GetElemenID(x, query)).ToList();

            //sort by name // id and name

            return result;
        }

        public override MethodDescription[] GetMethodNames()
        {
            return new MethodDescription[]{new MethodDescription{IsUserMethod = false} };
        }
    }
}
